package cn.wolfcode.luowowo.website.web.interceptor;

import cn.wolfcode.luowowo.cache.service.IUserInfoRedisService;
import cn.wolfcode.luowowo.member.domain.UserInfo;
import cn.wolfcode.luowowo.website.util.CookieUtil;
import cn.wolfcode.luowowo.website.web.annotation.RequireLogin;
import com.alibaba.dubbo.config.annotation.Reference;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * 登录检查
 */
public class CheckLoginInterceptor implements HandlerInterceptor {
    @Reference
    private IUserInfoRedisService userInfoRedisService;
    //登录检查
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
       UserInfo user = null;
        if(handler instanceof HandlerMethod){
           //判断方法上面是否贴有@RequireLogin标签
           HandlerMethod hm=(HandlerMethod) handler;
           if(hm.hasMethodAnnotation(RequireLogin.class)){
               //如果有进行登录 检查
               //获取token
               String token = CookieUtil.getToken(request,response);
               //通过token查redis进而产寻用户对象
                user = userInfoRedisService.getUserByToken(token);

                if (user==null){
                    response.sendRedirect("/login.html");
                    return false;
                }
           }
       }
        //request.getSession().setAttribute("userInfo",user);
        return true;//放行
    }
}
